

import React, { FC, useRef } from 'react'
import Photo from "../../assets/images/photo.png"
import { Avatar, List, Space } from 'antd-mobile'
import { connect } from 'react-redux'
import { baseURL } from '../../api/request'
import { Http } from '../../api'


const MyAvatar:FC<{
    userInfo:any,
    dispatch:any
}> = ({
    userInfo,
    dispatch
}) => {
    const file:any  = useRef()
    const startUpload = ()=>{
        file.current.click()
    }
    const uploadFile = async ()=>{
        console.log(file.current)
        const fileData = file.current.files[0]
        const data = new FormData()
        data.append("file",fileData)

        // 先上传文件
        let res:any = await Http.uploadfiles(data)
        if(res.code==200){
            let data:any = await Http.changeuserinfo({
                avatar:res.path
            })
            if(data.code == 200){
                userInfo.avatar = res.path;
                dispatch({
                    type:"getuserInfoAsync",
                    payload:{...userInfo}
                })
            }
        }
        // 再去修改后台数据 
    }
    return (
        <div>
            <input type="file" ref={file} style={{display:'none'}} onChange={uploadFile} />
            {
               userInfo &&  (userInfo.avatar ?
               <Avatar onClick={startUpload} src={userInfo.avatar.replace(/public/,baseURL)} className="avatar" style={{ '--size': '100px' }} />
               :
               <Avatar onClick={startUpload} src={Photo} className="avatar" style={{ '--size': '100px' }} />)
            }
        </div>
    )
}

export default connect(
    (state:any)=>{
        return {
            userInfo:state.getIn(['data','userInfo'])
        }
    }
)(MyAvatar)